package com.shelpe.services.sinbad;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@MapperScan(value="com.shelpe.services.sinbad.readdao",sqlSessionFactoryRef="readSqlSessionFactory",sqlSessionTemplateRef="readSqlSessionTemplate")
public class ReadDataBaseConfig {

	@Bean(name="readDataSource")
    public DataSource readDataSource(DataSourceProperties props) {
		DruidDataSource ds = new DruidDataSource();
		if(props != null){
			ds.setDriverClassName(props.getDriverClassName());
			ds.setUrl(props.getUrl());
			ds.setUsername(props.getUsername());
			ds.setPassword(props.getPassword());
		}
		ds.setMaxActive(20);
        return ds;
    }
	
	 @Bean(name="readSqlSessionFactory")
    public SqlSessionFactory readSqlSessionFactory(@Qualifier("readDataSource") DataSource ds) throws Exception {
 
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(ds);
 
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
 
        sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:/mybatis-config.xml"));
        
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/sqlmaps/read/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }
    
    @Bean(name="readSqlSessionTemplate")
    public SqlSessionTemplate readSqlSessionTemplate(@Qualifier("readSqlSessionFactory") SqlSessionFactory sf){
    	return new SqlSessionTemplate(sf);
    }
	
}
